import React, { useState } from 'react';
import cn from 'classnames';
import i from '@/index.module.css';
import recursionForm from '@/common/recursionForm';
import s from './style.module.css';
import { Table, Message, Dialog, Button, Confirm, Loading ,Form, Input, Datetime, Tooltip, Textarea, Select} from '@knownsec/react-component';
import { postToken,getToken,putToken,delToken} from '~/API';
// import SelectAnt from '@/components/SelectAnt';
import CopyText from '@/components/copy'
import EmptyData from '@/components/EmptyData';


import moment from 'moment';
export default function list() {
  const layout = {
    labelCol: { span: 3 },
    wrapperCol: { span: 18 },
  };
  const [refe] = useState(false);
  const [upVisible, setUpVisible] = useState('');
  const [selTable, setSelTable] = useState([]);
  const [tableData, setTableData] = useState({ data: [] });
  const [loading, setLoading] = useState(false)
  const apiForm = React.useRef();
  const disabledate = (current) => {
    return current < moment();
  };
  const getList = async () => {
    setLoading(true)
    setTableData([]);
    const list = await getToken();
    setTableData(list.data.data);
    setLoading(false)
  };
  React.useMemo(() => {
    getList();
  }, []);
  const submitInfo = async () => {
    const data=await apiForm.current.validateFields();
    data.is_active = data?.is_active[0] === "true" ? true : false
    let res=null
    let msg='';
    let type='success'
    if(upVisible==='获取Token'){
      res=await postToken(data).catch(err => {return err});
      if (res.status === 'success') {
        msg='添加成功'
      }else{
        const err=Object.keys(res.data)
        msg =res.data[err[0]][0];
        type='error'
      }
    }else{
      res=await putToken({id:selTable[0],data}).catch(err => {return err});
      if (res.status === 'success') {
        msg='修改成功'
      }else{
        const err=Object.keys(res.data)
        msg =res.data[err[0]][0];
        type='error'
      }
    }
    if(type=='success'){
      getList()
      setUpVisible(false);
      apiForm.current.resetFields();
    }
    Message.show({
      pro: true,
      className:[s.Message],
      showClose: false,
      type,
      message: msg,
    });
  }
  const columns = [
    {
      title: 'Token ID',
      dataIndex: 'token_id',
      render:(value) => {
        return (
          <Tooltip
            overlay={
              <p>Token ID：<CopyText text={value}/></p>
            }
            placement="topLeft"
          >
            <div className={s.td_omit}>
              {value}
            </div>
          </Tooltip>
        );
      }
    },
    {
      title: 'Token值',
      dataIndex: 'token',
      render:(value) => {
        return (
          <Tooltip
            overlay={
              <p>Token值：<CopyText text={value}/></p>
            }
            placement="topLeft"
          >
            <div className={s.td_omit}>

              {value}
            </div>
          </Tooltip>
        );
      }
    },
    {
      title: '创建时间',
      dataIndex: 'updated_at',
      className: s.td_12,
      render: (value) => (value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '--'),

    },
    {
      title: '过期时间',
      dataIndex: 'expired_time',
      className: s.td_12,
      render: (value) => (value ? moment(value).format('YYYY-MM-DD HH:mm:ss') : '--'),
    },
    {
      title: '备注',
      dataIndex: 'desc',
      render: (value) => {
        return (
          <Tooltip
            overlay={
              <p style={{ "max-width": ' 50vw', 'word-break': 'break-word' }}>备注：{value}</p>
            }
            placement="topLeft"
          >
            <div  className={s.td_omit}>
              {value|| '--'}
            </div>
          </Tooltip>
        );
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      className: s.w_5,
      render: (e, row) => {
        const id = row.id;
        return (
          <div className={s.btnBox}>
            <div
              className={s.operation}
              onClick={async () => {
                console.log('[ row ]-82', row)
                setSelTable([row.id])
                setUpVisible('修改Token');
                apiForm.current.setFieldsValue({token:row.token,expired_time:moment(row.expired_time),is_active:[row.is_active + ''],desc:row.desc});
              }}
            >
              修改
            </div>
            <div
              className={s.operation}
              onClick={() => {
                delList(id);
              }}
            >
              删除
            </div>
          </div>
        );
      },
    },
  ];
  const delList = (e) => {
    Confirm({
      pro: true,
      title: '提示',
      message: <div className="confirmbox">删除后，Token值立即失效，您确定要删除？</div>,
      onconfirm: async () => {
        const res = await delToken({id:e});
        console.log('[ res ]-129', res)
        getList();
        if (res.status === 'success') {
          Message.show({
            pro: true,
            className:[s.Message],
            showClose: false,
            type: 'success',
            message: '删除成功',
          });
        }
      },
      oncancel: () => {},
    });
  };
  const onValues = (data) => {
    let values = recursionForm(data);
    apiForm.current.setFieldsValue(values);
  };
  const validatormap = (rule, value, callback) => {
    if(value&&value.length>200){
      callback('最多输入200字符');
    }else{
      return Promise.resolve();
    }
  };
  return (
    <div className={s.wordMain}>
      <div className={s.tool}>
        <Button
          type="primary"
          pro
          disabled={tableData.length}
          onClick={() => {
            setUpVisible('获取Token');
          }}
        >
          获取Token
        </Button>
      </div>
      {/* <Loading show={loading} /> */}
      <Table
        refre={refe}
        tableLoading={loading}
        loadingLabel=""
        columns={columns}
        className={s.table}
        data={tableData}
        empty={<EmptyData/>}
      ></Table>
      <Dialog
        title={upVisible}
        visible={upVisible}
        confirmText=""
        cancelText=""
        className={s.w540}
        onhide={() => {
          setUpVisible(false);
          apiForm.current.resetFields();
        }}
      >
        <div className={cn(i.p24, s.addUser)}>
          <Form
            ref={apiForm}
            {...layout}
            onValuesChange={(newItem, allValues) => {
              onValues(newItem, allValues);
            }}
          >
            {upVisible!='获取Token'&&<Form.Item
              name="token"
              label="Token"
              rules={[{ required: true, message: '请获取Token值' }]}
            >
              <Input
                pro
                className={cn(i.dib, i.w300)}
                placeholder={'获取Token值'}
                autoComplete={'off'}
                disabled={true}
              />
            </Form.Item>}
            <Form.Item
              name="expired_time"
              label="有效期"
              rules={[{ required: true, message: '有效期不能为空' }]}
            >
              <Datetime disabledDate={disabledate} getPopupContainer={(triggerNode) => triggerNode} />
            </Form.Item>
            <Form.Item
              name="is_active"
              label="状态"
              initialValue={['true']}
            >
              <Select
                pro
                option={[
                  { label: '启用', value: 'true' },
                  { label: '禁用', value: 'false' },
                ]}
                className={s.w_30}
                placeholder="请选择状态"
              />
            </Form.Item>
            <Form.Item name="desc" label="备注" rules={[{ required: false, validator: validatormap}]}>
              <Textarea
                pro
                className={cn(i.dib, i.w300, s.textarea)}
                placeholder={'请输入备注'}
                autoComplete={'off'}
              />
            </Form.Item>
          </Form>
        </div>
        <div className={cn(i.tac, s.dioBtn)}>
          <Button className={i.vam} onClick={() => {setUpVisible(false);apiForm.current.resetFields();}}>
                        取消
          </Button>
          <Button
            type="primary"
            className={cn(i.ml24, i.vam)}
            onClick={() => submitInfo()}
          >
                        确定
          </Button>
        </div>
      </Dialog>
    </div>
  );
}
